package com.ccx.coachsite.ui.softmgr;


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteApiAccessor;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.downloadmgr.AsyncImageLoaderDetail;
import com.ccx.coachsite.downloadmgr.AsyncImageLoaderDetail.ImageCallback;
import com.ccx.coachsite.downloadmgr.DownloadItem;
import com.ccx.coachsite.downloadmgr.DownloadService;
import com.ccx.coachsite.downloadmgr.DownloadTool;
import com.ccx.coachsite.model.ServerDetailResult;
import com.ccx.coachsite.ui.login.LoginHelper;
import com.ccx.coachsite.util.FileUtil;
import com.ccx.coachsite.util.OpenShareTool;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.U;
import com.ccx.coachsite.weibo.WeiBoLoginActivity;
import com.ccx.coachsite.weibo.auth2.WeiBoContants;
import com.ccx.coachsite.weibo.auth2.WeiBoDBUtil;
import com.ccx.coachsite.weibo.auth2.net.Weibo;
import com.ccx.coachsite.weibo.auth2.net.WeiboException;
import com.ccx.coachsite.weibo.auth2.vo.LoginUser;


/**
 * 软件详情界面
 *
 */
public class SoftMgrDetailActivity extends Activity {
	
	/*------------控件变量-----------------*/
	private ImageView im_icon;
	private TextView tv_title;
	private ImageView im_star;
	private TextView tv_fee;
	private View sv_content_rl;
	private ScrollView sv_content;//内容主显示区
	private LinearLayout detail_bottom;
	private TextView tv_intro_main;//软件基本信息
	private TextView tv_intro_detail;//软件详细介绍
	private ImageView im_preview;//软件截图 
	private Button btn_left;
	private ImageButton btn_back;
	private TextView login_top_title;
	private Button login_top_right;
	private Button btn_onekeyshare; //用户叫一键分享（辅导员叫一键推荐）
	private LinearLayout ll_on_loading;//加载提示
	private LinearLayout ll_no_data;//未找数据时的提示
	private LinearLayout ll_on_loading_preImage;//加载预览图的加载提示
	private TextView tv_btn_all_info;//全部的介绍内容
	private LinearLayout ll_all_intro;
	private LinearLayout ll_on_loading_allintro;//加载全部介绍的提示
	private Gallery mGalleryLarge;		//滑动预览图
	private LargeImageAdapter largeImageAdapter;
	private BottomButtonClickListener btnClickListener=new BottomButtonClickListener();
	
	private LinearLayout detail_no_data;//未找数据时的提示
	private TextView tv_language;
	private TextView  tv_down_count;
	private TextView  tv_category;
	private TextView  tv_down_size;
	private TextView  tv_sdk;
	  
	/*------------------其他变量--------------*/
	private int iSoftID;
	private String softFlag;
	private SoftInfo mItem; //传进来的软件对象
	private Bitmap mDefIcon;
	private Bitmap mPreImage;
	private UninstallReceiver mUninstallReceiver;
	private DownloadStatusReceiver mDownloadStatusReceiver;//下载状态变化监听器
	private String mUserId;
	private int shareType; 	//应用类型  1.教程 2应用 3游戏 4专题

	//预览图导航
	private ImageView[] mImageViews;	
	private int mViewCount;		
	private int mCurSel;
	private LayoutInflater mInflater;
	
	/*------------------公共变量--------------*/
	private final int EVENT_COMMON=10000;//通用事件
	private final int EVENT_FIRST_LOADING=10001;//首次加载结束事件
	private final int EVENT_CONNECTION_FAILED=10002;//网络异常
	private final int EVENT_LOAD_ICON=10003;//软件图标加载完成
	private final int EVENT_LOAD_PREIMAGE=10004;//软件截图下载完成
	private final int EVENT_LOAD_ALL_INTRO=10005;//全部软件介绍下载完成
	private final int EVENT_LOADSOFT_FAILED=10006;//软件获取异常
	
	private final int EVENT_COLLECTION = 100010;//收藏结束
	private final int EVENT_COLLECTION_CANCLE = 100011;//取消收藏
	
	private static final int MESSAGE_ONE_KEY_SHARE_NO_LOGIN = 100020;//一键分享未找到已登录的用户	
	//一键分享时的"正在发布..."框
	private ProgressDialog shSinaPd;
	private final static int EVENT_CONNECT_FAILED=-10000;
	
	/**应用预览图的路径*/
	private String mAppScalePath = "";
	
	private Runnable mRunLoadIcon;
	private Runnable mRunLoadPreImage;
	private Runnable mRunLoadDetail;
//	private Runnable mRunLoadAllIntro;
	
	private Context mContext;
	private HandlerThread mHandlerThread;
	private Handler mTHandler; //非UI线程的Handler
	private Handler mEventHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			
			//首次加载结束
			case EVENT_FIRST_LOADING:
				//加载提示关闭
				ll_on_loading.setVisibility(View.GONE);
				String base=getString(R.string.soft_mgr_detail_base_ccx);
				String availVersion=mItem.getAvailVersion()==null?"":mItem.getAvailVersion();
				String size=mItem.getSid()==null?"0B":mItem.getSize();
				String language=mItem.getLanguage()==null?"":mItem.getLanguage();
				String dCount=mItem.getDownloadCount()==null?"0":mItem.getDownloadCount();
				String time=mItem.getUpdateTime()==null?"":mItem.getUpdateTime();
				String categoryName = mItem.getCategoryName();
				
				if (categoryName!=null && categoryName.length()>4) {
					categoryName = categoryName.substring(0, 3);
				}
				
				tv_language.setText("语言:"+language);
				tv_down_count.setText("下载:"+dCount);
				tv_category.setText("分类:"+categoryName);
				tv_down_size.setText("大小:"+size);
				tv_sdk.setText("版本号:"+availVersion);
				
				//tv_intro_main.setText(content); //软件介绍的基本内容
				String intro=mItem.getIntroduction()==null?"":mItem.getIntroduction();
				tv_intro_detail.setText(Html.fromHtml(intro));//软介绍的详细内容
				//判断是否所有的详细介绍都下载下来了，如果没有再取
//				long curLen=intro.length();
//				long totalLen=mItem.getIntroLength();
//				if(totalLen>curLen)
				if(true)//判断是否需要展开
				{
					ll_all_intro.setVisibility(View.VISIBLE);
					tv_btn_all_info.setOnClickListener(new ClickAllIntroListener());
				}
				sv_content_rl.setVisibility(View.VISIBLE);
				sv_content.setVisibility(View.VISIBLE);
				detail_bottom.setVisibility(View.VISIBLE);
				
				login_top_right.setTag(mItem.isCollection());
				login_top_right.setOnClickListener(mCollectionListener);
				if ( mItem.isCollection() ) {
					login_top_right.setBackgroundResource(R.drawable.soft_mgr_detail_collection_cancle);
				}else{
					login_top_right.setBackgroundResource(R.drawable.soft_mgr_detail_collection_btn);
				}
				
				loadPreImage();//开始加载预览图				
				break;
			//普通刷新
			case EVENT_COMMON:
				
				break;
			//网络连接失败提示
			case EVENT_CONNECTION_FAILED:
				//加载提示关闭
				ll_on_loading.setVisibility(View.GONE);
				ll_no_data.setVisibility(View.VISIBLE);
				TextView tv_nodata_error=(TextView) ll_no_data.findViewById(R.id.tv_nodata_error);
				Button btn_nodata_reflash=(Button) ll_no_data.findViewById(R.id.btn_nodata_reflash);
				tv_nodata_error.setText(R.string.common_no_connection);
				btn_nodata_reflash.setOnClickListener(new ReflashClickListener());
				btn_nodata_reflash.setVisibility(View.VISIBLE);
				break;
			//获取软件失败提示
			case EVENT_LOADSOFT_FAILED:
				//加载提示关闭
				ll_on_loading.setVisibility(View.GONE);
				ll_no_data.setVisibility(View.VISIBLE);
				TextView tv_nodata_error2=(TextView) ll_no_data.findViewById(R.id.tv_nodata_error);
				Button btn_nodata_reflash2=(Button) ll_no_data.findViewById(R.id.btn_nodata_reflash);
				tv_nodata_error2.setText("软件获取失败");
				btn_nodata_reflash2.setVisibility(View.GONE);
				
				sv_content_rl.setVisibility(View.GONE);
				sv_content.setVisibility(View.GONE);
				detail_bottom.setVisibility(View.GONE);
				detail_no_data.setVisibility(View.VISIBLE);
				
				break;				
			//软件图标加载完成
			case EVENT_LOAD_ICON:
				im_icon.setImageBitmap(mItem.getIcon());
				break;
			//软件截图下载完成
			case EVENT_LOAD_PREIMAGE:
				ll_on_loading_preImage.setVisibility(View.GONE);
				if(mPreImage!=null)
					im_preview.setImageBitmap(mPreImage);
				break;
			//软件全部介绍下载完成
			case EVENT_LOAD_ALL_INTRO:
				ll_on_loading_allintro.setVisibility(View.GONE);
				String res=(String) msg.obj;
				if(res!=null)
					tv_intro_detail.setText(res);
				else
					tv_btn_all_info.setVisibility(View.VISIBLE);
				break;
			case EVENT_COLLECTION:
				ServerDetailResult<Boolean> collectionResult =(ServerDetailResult<Boolean>) msg.obj;
				if (collectionResult!=null){
					if (collectionResult.isbNetworkProblem()){
						Toast.makeText(mContext, "网络错误", Toast.LENGTH_SHORT).show();
					}else if ( collectionResult.detailItem.booleanValue() ){
						login_top_right.setTag(true);
						login_top_right.setBackgroundResource(R.drawable.soft_mgr_detail_collection_cancle);
						Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(mContext, "收藏失败", Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case EVENT_COLLECTION_CANCLE:
				ServerDetailResult<Boolean> collectionCancleResult =(ServerDetailResult<Boolean>) msg.obj;
				if (collectionCancleResult!=null){
					if (collectionCancleResult.isbNetworkProblem()){
						Toast.makeText(mContext, "网络错误", Toast.LENGTH_SHORT).show();
					}else if ( collectionCancleResult.detailItem.booleanValue() ){
						login_top_right.setTag(false);
						login_top_right.setBackgroundResource(R.drawable.soft_mgr_detail_collection_btn);
						Toast.makeText(mContext, "取消收藏成功", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(mContext, "取消收藏失败", Toast.LENGTH_SHORT).show();
					}
				}
				break;
				//一键分享时没找到已登陆的用户，弹出登陆窗口
			case MESSAGE_ONE_KEY_SHARE_NO_LOGIN:
				shSinaPd.dismiss();
				//本没有授权过的帐号，进行用户授权
				Toast.makeText(mContext, getString(R.string.weibo_auth_tip), Toast.LENGTH_SHORT).show();
				//跳转到新浪微博帐号授权页面
				Intent weiboLogin=new Intent(mContext,WeiBoLoginActivity.class);
				weiboLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(weiboLogin, WeiBoContants.Login.REQUEST_CODE_WEIBO_LOGIN);
				break;
			}
		}
		
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		
		btn_onekeyshare.setText( "一键"+OpenShareTool.getShareDesc(mContext) );
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.soft_mgr_detail_ccx);
		mContext=this;
		mInflater = this.getLayoutInflater();
		
		//判断
		if ( CoachSiteApiAccessor.getAppContext()==null ) {
			CoachSiteApiAccessor.setAppContext(this);
		}
		
        mHandlerThread=new HandlerThread("thread");
        mHandlerThread.start();
        mTHandler=new Handler(mHandlerThread.getLooper());
        mDefIcon=BitmapFactory.decodeResource(getResources(), R.drawable.soft_mgr_defualt_icon);//默认图标
        mItem=(SoftInfo) getIntent().getSerializableExtra(DownloadItem.EXTRA_ME);
        
        shareType = getIntent().getIntExtra("shareType",2);//1.教程 2应用 3游戏 4专题
        
        mUserId = SharedPreferencesUtil.getValue(this, SharedKey.Shared_UserId_Key, mUserId);
        
        if ( "".equals(mUserId) ){
        	mUserId = "-1";
        }
        
        initView();
        
        if (mItem==null) {
        	 try {
        		 iSoftID = getIntent().getIntExtra("softID",0);
        		 softFlag = DownloadTool.getSoftFlag(getIntent().getStringExtra(DownloadTool.SOFT_FLAG));
        		 
        		 ServerDetailResult<SoftInfo> serverDetailResult = CoachSiteSoftMgrApiAccessor.getSoftAppDetail(iSoftID, mUserId, softFlag);
        		 mItem = serverDetailResult.detailItem;
        		 if (mItem==null) {
        			 sendMessage(mEventHandler,EVENT_LOADSOFT_FAILED);
        			 return ;
        		 }
        		 //下载某个软件
        		 /*
        		 Intent intent=new Intent(mContext,DownloadService.class);
        		 intent.putExtra("softID", Integer.parseInt(mItem.getSid()));
        		 startService(intent);
        		 */
     		} catch (Exception e) {
     			e.printStackTrace();
     			return;
     		}
        }               
        
        initViewTitleAndClick();
        
        //安装与卸载软件的监听
        mUninstallReceiver=new UninstallReceiver();
        IntentFilter infilter=new IntentFilter();
        infilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        infilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        infilter.addDataScheme("package");
        registerReceiver(mUninstallReceiver, infilter);
        
        //注册下载状态变化监听
  		IntentFilter dlStatusFilter=new IntentFilter();
  		dlStatusFilter.addAction(DownloadService.DOWNLOAD_STATUS_CHANGE_RECEIVER);
	    mDownloadStatusReceiver=new DownloadStatusReceiver();
	    registerReceiver(mDownloadStatusReceiver, dlStatusFilter);
	    
	    //添加分享点击统计
		int iShareMsgID = getIntent().getIntExtra("ShareCount", -1);
		if (iShareMsgID!=-1){
			CoachSiteSoftMgrApiAccessor.execShareMsgCount(iShareMsgID);
		}
		
		if (mItem!=null){
			CoachSiteSoftMgrApiAccessor.execOpenAppGameCount(mItem.getSid(), mContext);
		}
	}
	
	private void initView()
	{
		
		  detail_no_data=(LinearLayout)findViewById(R.id.detail_no_data);
		  tv_language = (TextView) findViewById(R.id.tv_language);
		  tv_down_count = (TextView) findViewById(R.id.tv_down_count);
		  tv_category = (TextView) findViewById(R.id.tv_category);
		  tv_down_size = (TextView) findViewById(R.id.tv_down_size);
		  tv_sdk = (TextView) findViewById(R.id.tv_sdk);
		  
		  im_icon=(ImageView)findViewById(R.id.im_icon);
		  tv_title=(TextView)findViewById(R.id.tv_title);
		  im_star=(ImageView)findViewById(R.id.im_star);
		  tv_fee=(TextView) findViewById(R.id.tv_fee);
		  //tv_intro_main=(TextView)findViewById(R.id.tv_develop);
		  tv_intro_detail=(TextView)findViewById(R.id.tv_intro_detail);
		  
		  im_preview=(ImageView)findViewById(R.id.im_preview);
		  
		  btn_left=(Button)findViewById(R.id.btn_left);
		  btn_back=(ImageButton)findViewById(R.id.login_btn_return);
		  btn_back.setOnClickListener(btnClickListener);
		  
		  login_top_title = (TextView)findViewById(R.id.login_top_title);
		  login_top_title.setText("详情");
		  login_top_right = (Button)findViewById(R.id.login_top_right);
		  login_top_right.setVisibility(View.VISIBLE);
		  btn_onekeyshare=(Button)findViewById(R.id.btn_onekeyshare);
		  sv_content_rl=findViewById(R.id.sv_content_rl);
		  sv_content=(ScrollView)findViewById(R.id.sv_content);
		  detail_bottom=(LinearLayout)findViewById(R.id.detail_bottom);
		  tv_btn_all_info=(TextView) findViewById(R.id.tv_btn_all_info);
		  ll_on_loading=(LinearLayout)findViewById(R.id.ll_on_loading);
		  ll_no_data=(LinearLayout)findViewById(R.id.ll_no_data);
		  ll_all_intro=(LinearLayout)findViewById(R.id.ll_all_intro);
		  ll_on_loading_preImage=(LinearLayout)findViewById(R.id.ll_on_loading_preImage);
		  ll_on_loading_allintro=(LinearLayout)findViewById(R.id.ll_on_loading_allintro);	
		  
		  mGalleryLarge = (Gallery)this.findViewById( R.id.im_preview_array );
		  largeImageAdapter = new LargeImageAdapter(mGalleryLarge);
		  mGalleryLarge.setAdapter( largeImageAdapter );
		//注册滑动选择器,动态变更预览图下的导航灯
			mGalleryLarge.setOnItemSelectedListener( new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
					
					if (position < 0 || position > mViewCount - 1 || mCurSel == position)    	{
			    		return ;
			    	} 
					mImageViews[mCurSel].setEnabled(true);
			    	mImageViews[position].setEnabled(false);    	
			    	mCurSel = position;				
				}
		
				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
			
			});
	}
	
	private void initViewTitleAndClick(){
		
		  tv_title.setText(mItem.getTitle());
		  //tv_fee.setText(mItem.getFee());//免费收费
		  initStar();
		  setBtnStatus();
		  
		  btn_left.setOnClickListener(btnClickListener);
		  btn_onekeyshare.setOnClickListener(btnClickListener);
		  setOneShareKeyButtonCaption();
		  
		  loadIcon();
		  initData();
	}
	
	/**
	 * 初始化星级
	 */
	private void initStar()
	{
		int iGrade  = (int)mItem.getGrade();
		switch (iGrade) {
		case 0:
			im_star.setImageResource(R.drawable.soft_mgr_star_0);
			break;
		case 1:
			im_star.setImageResource(R.drawable.soft_mgr_star_1);
			break;
		case 2:
			im_star.setImageResource(R.drawable.soft_mgr_star_2);
			break;
		case 3:
			im_star.setImageResource(R.drawable.soft_mgr_star_3);
			break;
		case 4:
			im_star.setImageResource(R.drawable.soft_mgr_star_4);
			break;
		case 5:
			im_star.setImageResource(R.drawable.soft_mgr_star_5);
			break;
		}
	}
	
	/**
	 * 设置按钮的状态
	 */
	private void setBtnStatus()
	{
		 switch (mItem.getStatus()) {
			//普通状态，显示为下载
			case DownloadItem.STATUS_NONE:
				btn_left.setText(R.string.common_button_download);
				break;
			//可升级状态，则显示升级
			case DownloadItem.STATUS_UPGRADABLE:
				btn_left.setText(R.string.common_upgrade);
				break;
			//正在下载状态，显示为取消下载
			case DownloadItem.STATUS_DOWNLOADING:
				btn_left.setText(getString(R.string.common_button_cancell)+getString(R.string.common_button_download));
				break;
			//暂停状态，显示为继续
			case DownloadItem.STATUS_DOWNLOAD_PAUSE:
				btn_left.setText(getString(R.string.common_button_continue)+getString(R.string.common_button_download));
				break;
			//已下载状态，显示为安装
			case DownloadItem.STATUS_DOWNLOADED:
				btn_left.setText(R.string.common_button_install);
				break;
			//已安装状态，显示为卸载
			case DownloadItem.STATUS_INSTALLED:
				btn_left.setText(R.string.common_button_uninstall);
				break;
			//下载失败状态，显示为下载
			case DownloadItem.STATUS_DOWNLOAD_FAILED:
				btn_left.setText(R.string.common_button_download);
				break;
			}//end switch
	}
	
	/**
	 * 初始化数据
	 */
	private void initData()
	{
		ll_no_data.setVisibility(View.GONE);
		sv_content_rl.setVisibility(View.GONE);
		sv_content.setVisibility(View.GONE);
		detail_bottom.setVisibility(View.GONE);
		ll_on_loading.setVisibility(View.VISIBLE);
		
		loadSoftDetail();
	}
	
	/**
	 * 加载软件详细信息
	 */
	private void loadSoftDetail()
	{
		mRunLoadDetail=new Runnable() {
			
			@Override
			public void run() {
//				String url=null;
//				if(SUtil.isZhLanguage())
//					url=reqUrl_zh;
//				else
//					url=reqUrl_en;
				try {
					//SoftMgrUtil.setSoftDetail(mContext, mItem);
				} catch (Exception e) {
					if((e instanceof MalformedURLException)||(e instanceof IOException)){ //网络异常
						sendMessage(mEventHandler,EVENT_CONNECTION_FAILED);
						return;
					}else
						e.printStackTrace();
				}
				
				sendMessage(mEventHandler,EVENT_FIRST_LOADING);
				loadPreImage();
			}
		};
		mTHandler.post(mRunLoadDetail);
	}
	
	/**
	 * 加载软件截图
	 */
	private void loadPreImage()
	{
		ll_on_loading_preImage.setVisibility(View.GONE);
		largeImageAdapter.setImgsList(mItem.preImageUrlsList);
		largeImageAdapter.notifyDataSetChanged();
		
		/*
		ll_on_loading_preImage.setVisibility(View.VISIBLE);
		mRunLoadPreImage=new Runnable() {
			
			@Override
			public void run() {
				try {
					mPreImage=getBitmap(mItem.preImageUrlsList.get(0), null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				sendMessage(mEventHandler, EVENT_LOAD_PREIMAGE);
			}
		};
		
		mTHandler.post(mRunLoadPreImage);
		*/
	}
	
	/**
	 * 加载软件图标
	 */
	private void loadIcon()
	{
		mRunLoadIcon=new Runnable() {
			
			@Override
			public void run() {
				Bitmap icon=getBitmap(mItem.getIconUrl(), mDefIcon);
				mItem.setIcon(icon);
				sendMessage(mEventHandler,EVENT_LOAD_ICON);
			}
		};
		
		mTHandler.post(mRunLoadIcon);
		
	}
	
	/**
	 * 获取图片
	 * @param imageUrl
	 * @param defBmp
	 * @return
	 */
	private Bitmap getBitmap(String imageUrl,Bitmap defBmp)
	{
		Bitmap bmp=null;
		try {
			//从url路径中抽取文件名
			String fileName=FileUtil.getFileNameFromPath(imageUrl, true);
			
			//缓存目录是否已经存在该图片
			boolean flag=FileUtil.isFileExits(SystemConst.DOWNLOAD_DIR, fileName);
			
			//缓存中存该图片了，取缓存图片
			if(flag)
				bmp=BitmapFactory.decodeFile(SystemConst.DOWNLOAD_DIR+fileName);
			else{
				HttpURLConnection conn=null;
				try {
					URL url=new URL(imageUrl);
					conn=(HttpURLConnection) url.openConnection();
					conn.setDoInput(true);
					conn.setConnectTimeout(60000);
					conn.setReadTimeout(5000);
					conn.connect();
					bmp=BitmapFactory.decodeStream(conn.getInputStream());
				} catch (Exception e) {
					bmp=null;
				} finally{
					if(conn!=null)
						conn.disconnect();
				}
				
				//网络上没取到图片，使用默认图片
				if(bmp==null)
					bmp=defBmp;
				else
					//将图片保存到缓存目录
					FileUtil.saveImageFile(SystemConst.DOWNLOAD_DIR, fileName, bmp);
			}
			
		} catch (Exception e) {
			
			//出错时用默认图标
			bmp=defBmp;
		}
		
		return bmp;
	}
	
	/**
	 * 发送Handler消息
	 * @param what
	 */
	private void sendMessage(Handler handler,int what)
	{
		Message msg=new Message();
		msg.what=what;
		handler.sendMessage(msg);
	}
	
	private void talk(String msg)
	{
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}
	
	
	/**
	 * 资源释放
	 */
	private void rcImageView(){
		//释放Image资源		
		if (mImageViews==null) return;
		
  	    for (int i = 0; i < mImageViews.length; ++i){
  	    	ImageView imgView = mImageViews[i];
  	    	if ( imgView!=null ) { 
	          	Drawable drawable = imgView.getDrawable();
	          	if (drawable != null) {
	          		drawable.setCallback( null );
	            }                     
  	    	}
  	    }

    	System.gc();
	}
	
	@Override
	protected void onDestroy() {
		
		rcImageView();
		
		if (null!=mItem){
		
			unregisterReceiver(mUninstallReceiver);
			unregisterReceiver(mDownloadStatusReceiver);
			mTHandler.removeCallbacks(mRunLoadDetail);
			mTHandler.removeCallbacks(mRunLoadIcon);
			mTHandler.removeCallbacks(mRunLoadPreImage);
			if(mPreImage!=null&&!mPreImage.isRecycled())
			{
				mPreImage.recycle();
				mPreImage=null;
			}
			if(mDefIcon!=null&&!mDefIcon.isRecycled())
			{
				mDefIcon.recycle();
				mDefIcon=null;
			}
			Bitmap tmpBmp=mItem.getIcon();
			if(tmpBmp!=null&&!tmpBmp.isRecycled())
			{
				tmpBmp.recycle();
				tmpBmp=null;
			}
		}		
		super.onDestroy();
	}



	/*-----------------------------内部类区-------------------------------------*/
	/**
	 * 未找数据时，刷新按钮的点击事件
	 */
	private class ReflashClickListener implements OnClickListener
	{

		@Override
		public void onClick(View v) {
			initData();
		}
		
	}
	
	/**
	 * 底部按钮点击事件
	 */
	private class BottomButtonClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			if(v.getId()==R.id.btn_left) //左边按钮被点击
			{
				switch (mItem.getStatus()) {
				//普通状态，则下载
				case DownloadItem.STATUS_NONE:
					beginDownload();
					finish();
					break;
				//可升级状态，则下载
				case DownloadItem.STATUS_UPGRADABLE:
					beginDownload();
					finish();
					break;
				//正在下载状态，则取消下载
				case DownloadItem.STATUS_DOWNLOADING:
					Intent cancelIntent=new Intent(DownloadService.RECEIVER_CANCEL_DOWNLOAD);
					cancelIntent.putExtra(DownloadItem.EXTRA_ME, mItem);
					mContext.sendBroadcast(cancelIntent);
					talk(mItem.getTitle()+":"+getString(R.string.common_cancel_download));
					finish();
					break;
				//暂停状态，则继续下载
				case DownloadItem.STATUS_DOWNLOAD_PAUSE:
					DownloadService.continueItem(mItem,mContext);
					talk(mItem.getTitle()+":"+getString(R.string.common_begin_download));
					finish();
					break;
				//已下载状态，则安装
				case DownloadItem.STATUS_DOWNLOADED:
					U.installApplication(mContext, mItem);
					break;
				//已安装状态，则卸载
				case DownloadItem.STATUS_INSTALLED:
					U.uninstallApp(mContext, mItem);
					break;
				//下载失败状态，则下载
				case DownloadItem.STATUS_DOWNLOAD_FAILED:
					beginDownload();
					finish();
					break;
				}//end switch
				
			}
			
			if ( v.getId()==R.id.login_btn_return ){ 
				finish();
			}
			
			if ( v.getId()==R.id.btn_onekeyshare ){ 
				//share();
				//weiBoCheck();				
				OpenShareTool.showOperDialog(SoftMgrDetailActivity.this, mItem.getTitle() ,mItem.getDownloadUrl() , iSoftID+"", shareType, "", softFlag);
			}
			
		}
		
		
		/**
		 * 分享
		 */
		private void share() {
			
			String content=getString(R.string.soft_mgr_detail_share_txt);
			content=content.replace("{0}", "url地址");
			//Uri uri=Uri.parse("file://"+mPic); 
			
			Intent it = new Intent(Intent.ACTION_SEND);
			String[] tos = { "" }; // 收件人地址
			it.putExtra(Intent.EXTRA_EMAIL, tos);
			it.putExtra(Intent.EXTRA_TEXT, content);
			it.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.soft_mgr_detail_share_subject));
			//it.putExtra(Intent.EXTRA_STREAM, uri);
			// it.setType("message/rfc822"); // Email类型
			it.setType("text/plain");
			it.putExtra("sms_body", content);
			startActivity(Intent.createChooser(it, getString(R.string.home_apps_share_title)));
		}
		
		/**微博用户登陆信息*/
		private LoginUser mWeiBoLoginUser;
		/**
		 * 检测本地是否有授权过的新浪微博帐号
		 */
		private void weiBoCheck()
		{
			shSinaPd=new ProgressDialog(mContext);
			shSinaPd.setMessage(getString(R.string.weibo_on_sending));
			shSinaPd.show();
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					
					if(mWeiBoLoginUser==null)
						mWeiBoLoginUser=WeiBoDBUtil.getLoginUser(mContext);
					if(mWeiBoLoginUser!=null)
						//发布微博
						sendWeiBoToSina();
					else{
						
						mEventHandler.sendEmptyMessage(MESSAGE_ONE_KEY_SHARE_NO_LOGIN);
					}
				}
			}).start();
		}				
		
		//一键分享到新浪的发布事件处理
		private Handler mWeiBoSendHandler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
				shSinaPd.dismiss();
				switch (msg.what) {
				case WeiBoContants.Auth.OK:
					//发布成功
					Toast.makeText(mContext, getString(R.string.weibo_send_success), Toast.LENGTH_SHORT).show();
					break;
				case EVENT_CONNECT_FAILED:
					Toast.makeText(mContext, getString(R.string.hit_network_problem), Toast.LENGTH_SHORT).show();
					break;
				//登陆过期 ,重新登陆
				case WeiBoContants.STATUS_CODE_TOKEN_INVALIDATE:
					mEventHandler.sendEmptyMessage(MESSAGE_ONE_KEY_SHARE_NO_LOGIN);
					break;
				case -1:
					//发布失败
					Toast.makeText(mContext, getString(R.string.weibo_send_failed), Toast.LENGTH_SHORT).show();
					break;
				default:
					String toastContent=WeiBoContants.getCause(msg.what);
					if(TextUtils.isEmpty(toastContent))
						toastContent=getString(R.string.weibo_send_failed);
					Toast.makeText(mContext, toastContent, Toast.LENGTH_SHORT).show();
					break;
				}
				
			}
			
		};
		
		/**
		 * 分享主题到新浪微博
		 * @return
		 */
		private void sendWeiBoToSina()
		{		
			//微博的内容，其中主题的下载地址，国内与国外不同
			String content=getString(R.string.txt_share_txt);

			content=content.replace("{0}", "http://mobile.91.com/Theme/Android/"+mItem.getSid()+".html");
		
			//final File file=new File(mAppScalePath);
			int handleCode=-1;
			try {
				Weibo weibo=Weibo.getInstance(mContext);
				boolean b=weibo.uploadStatus(content, null, mWeiBoLoginUser.getAccessToke());
				handleCode=WeiBoContants.Auth.OK;
			} catch (Exception e) {
				if((e instanceof MalformedURLException)||(e instanceof IOException)||(e instanceof SocketTimeoutException)) //网络异常
					handleCode=EVENT_CONNECT_FAILED;
				if(e instanceof WeiboException)
					handleCode=((WeiboException)e).getStatusCode();
				e.printStackTrace();
			}
			Message msg=new Message();
			msg.what=handleCode;
			mWeiBoSendHandler.sendMessage(msg);		
		}
		
		
		/**
		 * 开始下载
		 */
		private void beginDownload()
		{
			if(mItem!=null)
			{ 
				new Thread(new Runnable() {

					@Override
					public void run() {
						Intent intent=new Intent(mContext,DownloadService.class);
						intent.putExtra(DownloadItem.EXTRA_ME, mItem);
						mContext.startService(intent);
					}
					
				}).start();
				
				talk(mItem.getTitle()+":"+getString(R.string.common_begin_download));
			}
		}
		
	}//end BottomButtonClickListener
	
	/**
     * 安装与卸载监听
     *
     */
    private class UninstallReceiver extends BroadcastReceiver {
    	@Override
    	public void onReceive(Context context, Intent intent) {
    		if (mItem==null)
    			return;
    		String action=intent.getAction();
    		String dataStr=intent.getDataString();
    		if(dataStr!=null&&dataStr.substring(8).equalsIgnoreCase(mItem.getPkgName()))
    		{
    			if(action.equals(Intent.ACTION_PACKAGE_ADDED))//安装
        		{
        			mItem.setStatus(DownloadItem.STATUS_INSTALLED);//状态设置成已安装
        			NotificationManager nm=(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        			nm.cancel(Integer.parseInt(mItem.getSid()));
        		}else if(action.equals(Intent.ACTION_PACKAGE_REMOVED)){ //卸载
        			int status=DownloadService.getDownloadStatus(mContext, mItem);
        			mItem.setStatus(status);//状态设置成已安装
        		}
    			setBtnStatus();
    		}
    		
    		
    	}
	}// end UninstallReceiver
    
    /**
     * 下载状态改变监听器
     */
    private class DownloadStatusReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mItem==null)
    			return;
			DownloadItem dItem=(DownloadItem) intent.getSerializableExtra(DownloadItem.EXTRA_ME);
			if(dItem!=null){
				if( mItem.getSid().equalsIgnoreCase(dItem.getSid()) ){
					mItem.setStatus(dItem.getStatus());
					setBtnStatus();
				}
			}
		}
    }//end DownloadStatusReceiver
    
    /**
	 * 全部介绍按钮点击事件
	 */
	private class ClickAllIntroListener implements OnClickListener{
		private boolean showAll = false;
		@Override
		public void onClick(View v) {
			if(showAll){
				tv_intro_detail.setMaxLines(4);
				tv_btn_all_info.setText(R.string.common_show_all);
				tv_btn_all_info.setSelected(false);
				showAll = false;
			}else{
				tv_intro_detail.setMaxLines(999);
				tv_btn_all_info.setText(R.string.common_show_brief);
				tv_btn_all_info.setSelected(true);
				showAll = true;
			}
		}
    	
    } // end ClickAllIntroListener

	//收藏取消按钮事件
	View.OnClickListener mCollectionListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			
			if (!LoginHelper.requireLogin(mContext))
				return;
			
			boolean isCollect = (Boolean)v.getTag();
			
			if ( isCollect ){
				//取消
				new Thread(new Runnable() {

					@Override
					public void run() {
						ServerDetailResult<Boolean> collectionResult = CoachSiteSoftMgrApiAccessor.collectionCancleApp(iSoftID,mUserId);
						Message msg = mEventHandler.obtainMessage(EVENT_COLLECTION_CANCLE, collectionResult);
						msg.sendToTarget(); 
					}
					
				}).start();
			}else{
				//收藏
				new Thread(new Runnable() {

					@Override
					public void run() {
						ServerDetailResult<Boolean> collectionResult = CoachSiteSoftMgrApiAccessor.collectionApp(iSoftID,mUserId);
						Message msg = mEventHandler.obtainMessage(EVENT_COLLECTION, collectionResult);
						msg.sendToTarget();
					}
					
				}).start();
			}
		}
		
	};
	
	
	/**
	 * 当前预览图适配器
	 */
	class LargeImageAdapter extends BaseAdapter {
		
		private Gallery galleryLarge;
		
		private AsyncImageLoaderDetail mAsyncImageLoader;
		
		/**
		 * 预览图列表
		 */
		private List<String> imgsUrlList = new ArrayList<String>();
		
		public LargeImageAdapter(Gallery galleryLarge){
			this.galleryLarge = galleryLarge;
			mAsyncImageLoader = new AsyncImageLoaderDetail();
		}
		
		
		public void setImgsList( ArrayList<String> imgsList) {
			
			this.imgsUrlList.clear();
			this.imgsUrlList.addAll( imgsList );
			
			//设置导航灯
			LinearLayout guideLinearLayout = (LinearLayout) findViewById(R.id.layout_large_image_guide_LinearLayout);
			mViewCount = getCount();
			if ( mViewCount>5 ) 
				mViewCount = 5;
			//最多显示5张预览图
			if ( mViewCount>0 ){ 				
							
				//图片导航灯初始化
				if (mImageViews!=null) {
					for (int i = 0; i < mImageViews.length; ++i){
						if (mImageViews[i]!=null){
							mImageViews[i].setVisibility(View.INVISIBLE);
						}
					}
					
					galleryLarge.setSelection(0);
				}else{
					mImageViews = new ImageView[5]; //最多显示五张图   
				}
				
		    	for(int i = 0; i < mViewCount; i++){
		    		mImageViews[i] = (ImageView) guideLinearLayout.getChildAt(i);
		    		mImageViews[i].setVisibility(View.VISIBLE);
		    		mImageViews[i].setEnabled(true);
		    		mImageViews[i].setTag(i);
		    	}    	
		    	mCurSel = 0;
		    	mImageViews[mCurSel].setEnabled(false);
			}
		}
		
		public int getCount() {
			return imgsUrlList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			View view = convertView;

			ItemCache cache = null;
			if (null == view) {
				view = mInflater.inflate(R.layout.soft_mgr_detail_ccx_image_item, null);
				cache = new ItemCache(view);
		        
				view.setTag(cache);
			} else {
				cache = (ItemCache) view.getTag();
			}					
			
			String previewImageUrl = imgsUrlList.get(position);	
			cache.largePreImg.setTag(previewImageUrl);		
			Drawable cachedImage = mAsyncImageLoader.loadDrawable(previewImageUrl, new ImageCallback() {
	            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
	            	if ( galleryLarge ==null )return; 
	                ImageView imageViewByTag = (ImageView) galleryLarge.findViewWithTag(imageUrl);
	                
	                if (imageViewByTag != null && imageDrawable!=null) {
	                    imageViewByTag.setImageDrawable(imageDrawable);
	                    AlphaAnimation aa = new AlphaAnimation(0.7f, 1.0f);
	                    aa.setDuration(300);
	                    imageViewByTag.startAnimation(aa);	
	                }	                
	            }
	        });
			if (cachedImage == null) {
				cache.largePreImg.setImageResource(R.drawable.soft_loading_default);
			}else{						
				cache.largePreImg.setImageDrawable(cachedImage);					
			}	
			return view;
		}

		//释放资源
		public void clearRes(){
			galleryLarge = null;
			imgsUrlList.clear();
			mAsyncImageLoader.releaseImageCache();			
		}
	}
	
	private class ItemCache {
		public ImageView largePreImg;
		
		public ItemCache(View view) {
			largePreImg = (ImageView) view.findViewById(R.id.im_preview);
		}
	}
	
	/**
	 * 根据用户类型设置按钮标题
	 */
	private void setOneShareKeyButtonCaption(){
		
		if ( LoginHelper.isLogin(mContext) ) {
		
			boolean isExport = SharedPreferencesUtil.getBoolean(mContext, SharedKey.Shared_Is_Expert);
			if (isExport) {
				btn_onekeyshare.setText(R.string.soft_mgr_detail_onekeyRecommend);
			}
		}
	}
}
